package service

import (
	"context"
	"errors"
	"lion-passport/internal/dao/model"
	"lion-passport/internal/dao/query"
	"lion-passport/internal/utils/log"

	"gorm.io/gorm"
)

func CreateUser(user *model.User, ctx context.Context) (u *model.User, err error) {
	dbUser, err := query.User.WithContext(ctx).Where(query.User.UserID.Eq(user.UserID)).First()
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			log.LogrusObj.Infof("User with userId %d not found, creating new user", user.UserID)
		} else {
			return nil, err
		}
	}
	if dbUser == nil {
		err = query.User.Create(user)
		if err != nil {
			return nil, err
		}
		u = user
	} else {
		log.LogrusObj.Infof("User with userId %d already exists, skipping creation", user.UserID)
		u = dbUser
	}

	return u, nil
}

func GetUserByUid(id int32, ctx context.Context) (user *model.User, err error) {
	dbUser, err := query.User.WithContext(ctx).Where(query.User.UserID.Eq(id)).First()
	if err != nil {
		return nil, err
	}
	if dbUser == nil {
		return nil, nil // User not found
	}
	return dbUser, nil
}

func UpdateUserById(id int32, user *model.User, ctx context.Context) (userNew *model.User, err error) {
	u := query.User
	ret, err := u.WithContext(ctx).Where(u.UserID.Eq(id)).Updates(user)
	if err != nil {
		log.LogrusObj.Errorf("Failed to update user with ID %d: %v", id, err)
	}
	if ret.Error != nil {
		log.LogrusObj.Errorf("Failed to update user with ID %d: %v", id, ret.Error)
		return nil, err
	}
	existingUser, err := u.WithContext(ctx).Where(u.UserID.Eq(id)).First()
	userNew = existingUser
	if err != nil {
		return nil, err
	}
	if existingUser == nil {
		return nil, errors.New("user not found") // User not found
	}

	return userNew, nil
}
